package com.xiemulei.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiemulei.common.to.mq.SeckillOrderTo;
import com.xiemulei.common.utils.R;
import com.xiemulei.common.vo.MemberResponseVo;
import com.xiemulei.gulimall.seckill.feign.CouponFeignClient;
import com.xiemulei.gulimall.seckill.feign.ProductFeignClient;
import com.xiemulei.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.xiemulei.gulimall.seckill.service.SeckillService;
import com.xiemulei.gulimall.seckill.to.SeckillSkuRedisTo;
import com.xiemulei.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.xiemulei.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Resource
    CouponFeignClient couponFeignClient;

    @Resource
    ProductFeignClient productFeignClient;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    RedissonClient redissonClient;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignClient.getLatest3DaysSession();
        if (r.getCode() == 0) {
            List<SeckillSessionWithSkusVo> sessionsWithSkusVo = r.getData(new TypeReference<>() {
            });
            saveSessionInfo(sessionsWithSkusVo);
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 当前时间属于哪个秒杀场次
        long now = new Date().getTime();

        try (Entry seckillSkus = SphU.entry("seckillSkus")) {
            Set<String> keys = stringRedisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            assert keys != null;
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (now >= start && now <= end) {
                    List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
                    assert range != null;
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        return list.stream().map(item -> JSON.parseObject(item, SeckillSkuRedisTo.class)).toList();
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流，{}", e.getMessage());
        }


        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        String regx = "(\\d+)-" + skuId;
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    assert skuRedisTo != null;
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    long current = System.currentTimeMillis();
                    if (current >= startTime && current <= endTime) {
                    } else {
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        long s1 = System.currentTimeMillis();
        //获取当前用户的信息
        MemberResponseVo user = LoginUserInterceptor.loginUser.get();

        //1、获取当前秒杀商品的详细信息从Redis中获取
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        String skuInfoValue = hashOps.get(killId);
        if (!StringUtils.hasLength(skuInfoValue)) {
            return null;
        }

        //(合法性效验)
        SeckillSkuRedisTo redisTo = JSON.parseObject(skuInfoValue, SeckillSkuRedisTo.class);
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long currentTime = System.currentTimeMillis();
        //判断当前这个秒杀请求是否在活动时间区间内(效验时间的合法性)
        if (currentTime >= startTime && currentTime <= endTime) {
            //2、校验随机码和商品id
            String randomCode = redisTo.getRandomCode();
            String redisSkuId = redisTo.getPromotionSessionId() + "-" + redisTo.getSkuId();
            if (randomCode.equals(key) && killId.equals(redisSkuId)) {
                //3、验证购物数量是否合理和库存量是否充足
                Integer seckillLimit = redisTo.getSeckillLimit();
                //获取信号量
                String seckillCount = stringRedisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE + randomCode);
                assert seckillCount != null;
                int count = Integer.parseInt(seckillCount);
                //判断信号量是否大于0,并且买的数量不能超过库存
                if (count > 0 && num <= seckillLimit && count > num) {
                    //4、验证这个人是否已经买过了（幂等性处理）,如果秒杀成功，就去占位。userId-sessionId-skuId
                    //SETNX 原子性处理
                    String redisKey = user.getId() + "-" + redisSkuId;
                    //设置自动过期(活动结束时间-当前时间)
                    long ttl = endTime - currentTime;
                    Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (Boolean.TRUE.equals(aBoolean)) {
                        //占位成功说明从来没有买过,分布式锁(获取信号量-1)
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        //TODO 秒杀成功，快速下单
                        boolean semaphoreCount = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                        //保证Redis中还有商品库存
                        if (semaphoreCount) {
                            //创建订单号和订单信息发送给MQ
                            // 秒杀成功 快速下单 发送消息到 MQ 整个操作时间在 10ms 左右
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo orderTo = new SeckillOrderTo();
                            orderTo.setOrderSn(timeId);
                            orderTo.setMemberId(user.getId());
                            orderTo.setNum(num);
                            orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                            orderTo.setSkuId(redisTo.getSkuId());
                            orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                            long s2 = System.currentTimeMillis();
                            log.info("耗时..." + (s2 - s1));
                            return timeId;
                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionInfo(List<SeckillSessionWithSkusVo> sessions) {
        if (sessions != null) {
            sessions.forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(key))) {
                    List<String> seckillSkuIds = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "-" + item.getSkuId().toString()).toList();
                    stringRedisTemplate.opsForList().leftPushAll(key, seckillSkuIds);
                    saveSessionSkuInfo(session);
                }
            });
        }
    }

    private void saveSessionSkuInfo(SeckillSessionWithSkusVo session) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        session.getRelationSkus().forEach(seckillSkuVo -> {
            SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();
            R r = productFeignClient.getSkuInfo(seckillSkuVo.getSkuId());
            if (r.getCode() == 0) {
                SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<>() {
                });
                skuRedisTo.setSkuInfo(skuInfoVo);
            }

            BeanUtils.copyProperties(seckillSkuVo, skuRedisTo);

            skuRedisTo.setStartTime(session.getStartTime().getTime());
            skuRedisTo.setEndTime(session.getEndTime().getTime());

            String token = UUID.randomUUID().toString().replace("-", "");
            skuRedisTo.setRandomCode(token);

            //序列化json格式存入Redis中
            String seckillValue = JSON.toJSONString(skuRedisTo);
            hashOps.put(seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString(), seckillValue);

            //如果当前这个场次的商品库存信息已经上架就不需要上架
            //5、使用库存作为分布式Redisson信号量（限流）
            // 使用库存作为分布式信号量
            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
            // 商品可以秒杀的数量作为信号量
            semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
        });
    }
}
